package com.voltmao.webpro.utils.file;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class DocUtil {

    private Configuration configure = null;
    public DocUtil(){
        configure = new Configuration();
        configure.setDefaultEncoding("utf-8");
    }

    /**
     * 根据Doc模板生成word文件
     * @param dataMap Map 需要填入模板的数据
     * @param downloadType 文件名称
     * @param savePath 保存路径
     */

    public File createDoc(Map<String, Object> dataMap, String downloadType, String savePath){
        File outFile = new File(savePath);
        try{
            //加载需要装填的模板
            Template template  = null;
            //加载模板文件
            configure.setClassForTemplateLoading(this.getClass(),"../file");
//               configure.setDirectoryForTemplateLoading(new File("C:\\Users\\zhang_lin\\Desktop\\testDoc"));
//               configure.setServletContextForTemplateLoading(getServletContext(), "/doc");
            //设置对象包装器
            configure.setObjectWrapper(new DefaultObjectWrapper());
            //设置异常处理器
            configure.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
            configure.setDefaultEncoding("utf-8");

            //定义Template对象,注意模板类型名字与downloadType要一致
            template= configure.getTemplate(downloadType + ".ftl");
            //输出文档

            Writer out = null;
            out= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
            template.process(dataMap,out);
            out.close();
//               outFile.delete();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return outFile;
    }

    public File doc2pdf(String fromPath, String toPath){
        return null;
    }

    public static void main(String[] args) {
        DocUtil doc = new DocUtil();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("name","张三");
        doc.createDoc(dataMap,"test","D:\\tests.doc");
    }
}
